// uploadFile.js
const {runCommand} = require ('./handleCommand')
const getCurrentTime = require ('./handleTime')
const chalk = require("chalk");
const log = console.log;
// 文件上传(ssh对象、配置信息、本地待上传文件)
async function uploadFile (ssh, config, localFile) {
  return new Promise((resolve, reject) => {
    log(chalk.blue('开始文件上传...'))
    handleSourceFile(ssh, config)
    ssh.putFile(localFile, config.deployDir +'/'+ config.targetFile).then(async () => {
      resolve(log(chalk.green('文件上传完成')))
    }, (err) => {
      reject(log(chalk.red('上传失败！', err)))
    })
  })
}

// 处理源文件(ssh对象、配置信息)
async function handleSourceFile (ssh, config) {
  if (config.openBackUp) {
    log(chalk.blue('已开启远端备份!'))
    await runCommand(
      ssh,
      `
      if [ -d ${config.releaseDir} ];
      then mv ${config.releaseDir} ${config.releaseDir}_backup_in_${getCurrentTime()}
      fi
      `,
      config.deployDir)
  } else {
    log(chalk.blue('提醒：未开启远端备份!'))
    await runCommand(
      ssh,
      `
      if [ -d ${config.releaseDir} ];
      then mv ${config.releaseDir} /tmp/${config.releaseDir}_backup_in_${getCurrentTime()}
      fi
      `,
      config.deployDir)
  }
}

module.exports = uploadFile